 
use std::any::Any;
use std::collections::HashMap;
use std::sync::{Arc, Mutex};

use crate::core::beans::bean::{Bean, BeanManager, IDestructible};

/// 定义扩展生命周期中的标准事件名称
pub mod expansion_lifecycle_event_names {
    pub const BEFORE_EXTENSION_ACTIVATE: &str = "beforeExtensionActivate";
    pub const ON_EXTENSION_ACTIVATED: &str = "onExtensionActivated";
    pub const BEFORE_EXTENSION_DEACTIVATE: &str = "beforeExtensionDeactivate";
    pub const ON_EXTENSION_DEACTIVATED: &str = "onExtensionDeactivated";
    pub const ON_DYNAMIC_CONTRIBUTES_ADDED: &str = "onDynamicContributesAdded";
    pub const ON_DYNAMIC_CONTRIBUTES_REMOVED: &str = "onDynamicContributesRemoved";
    pub const ON_DYNAMIC_CONTRIBUTION_POINTS_ADDED: &str = "onDynamicContributionPointsAdded";
    pub const ON_DYNAMIC_CONTRIBUTION_POINTS_REMOVED: &str = "onDynamicContributionPointsRemoved";
}

// 定义事件监听器的类型。为了简单，我们让所有事件都接收一个 Any 类型的 payload。
pub type EventListener = Box<dyn Fn(Arc<dyn Any + Send + Sync>) + Send + Sync>;

/// 事件管理器
pub struct EventManager {
    event_stack: Arc<Mutex<HashMap<String, Vec<Arc<EventListener>>>>>,
}

impl IDestructible for EventManager {
    fn destructor(&self) {
        self.event_stack.lock().unwrap().clear();
        println!("EventManager destroyed.");
    }
}

impl Bean for EventManager {
    /// `EventManager` 的构造函数
    fn new(_bean_manager: &Arc<BeanManager>) -> Arc<Self> {
        Arc::new(Self {
            event_stack: Arc::new(Mutex::new(HashMap::new())),
        })
    }
}

impl EventManager {
    /// 订阅一个事件
    /// 
    /// # Arguments
    /// * `event_name` - 事件名称
    /// * `listener` - 监听器闭包
    /// 
    /// # Returns
    /// * 一个“取消订阅”的闭包，调用它即可取消此次订阅。
    pub fn on(&self, event_name: &str, listener: EventListener) -> Box<dyn FnOnce() + Send + Sync> {
        let listener_arc = Arc::new(listener);
        self.event_stack
            .lock()
            .unwrap()
            .entry(event_name.to_string())
            .or_default()
            .push(listener_arc.clone());

        let event_stack_clone = self.event_stack.clone();
        let event_name_clone = event_name.to_string();
        
        Box::new(move || {
            let mut stack = event_stack_clone.lock().unwrap();
            if let Some(listeners) = stack.get_mut(&event_name_clone) {
                // 通过比较 Arc 的指针来移除特定的监听器
                listeners.retain(|l| !Arc::ptr_eq(l, &listener_arc));
            }
        })
    }

    /// 发布一个事件
    /// 
    /// # Arguments
    /// * `event_name` - 事件名称
    /// * `payload` - 传递给监听器的数据
    pub fn dispatch(&self, event_name: &str, payload: Arc<dyn Any + Send + Sync>) {
        let listeners = self.event_stack.lock().unwrap().get(event_name).cloned();
        if let Some(listeners) = listeners {
            for listener in listeners {
                // 在独立的 task 中执行，避免一个 listener 阻塞整个事件循环
                let payload_clone = payload.clone();
                tokio::spawn(async move {
                    listener(payload_clone);
                });
            }
        }
    }
}
